<template>
    <div class="app-container">
        <!-- 故障告警管理 -->
        <health-card :numLength="2" :overviewData="overviewData">
            <!-- 头 -->
            <template #cardTopNum>
                <overview-num-box :title="'实时告警数量'">
                    <span>{{ overviewData.currentAlarmQuantity }}个</span>
                </overview-num-box>
            </template>

            <!-- 底部 -->
            <template #cardItem>
                <div class="card_item">
                    <overview-box :title="'近一周故障告警趋势(平均分)'">
                        <qushi :chart-data="overviewData.monthAverage" :yAxisExtra="{ min: 90 }" />
                    </overview-box>
                </div>
                <div class="card_item">
                    <overview-box :title="'各区县故障告警平均分'">
                        <quxian :chart-data="overviewData.todayDistrictAverage" />
                    </overview-box>
                </div>
            </template>
        </health-card>

        <el-card shadow="always">
            <el-form :model="queryParams" :inline="true" label-width="100px">
                <el-form-item label="网络制式：" prop="networkType">
                    <el-select v-model="queryParams.networkType" placeholder="请选择网络制式" style="width: 240px">
                        <el-option v-for="dict in nhp_network_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属区县：" prop="county">
                    <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable style="width: 240px">
                        <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="站号" prop="stationNo">
                    <el-input v-model="queryParams.stationNo" placeholder="请输入站号" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="基站名称：" prop="stationName">
                    <el-input v-model="queryParams.stationName" placeholder="请输入基站名称" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="创建时间：" prop="createTime">
                    <el-date-picker v-model="queryParams.createStartEnd" type="daterange" start-placeholder="开始时间"
                        end-placeholder="结束时间" :size="size" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="listAlarmTable">查询</el-button>
                    <el-button @click="unsetQueryForm"><el-icon>
                            <RefreshRight />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="always" style="margin-top: 10px;min-height: 500px;padding-bottom: 3px;">
            <el-row>
                <!-- <el-button type="primary" icon="Download" @click="refExportDialog.show(queryParams)">导出</el-button> -->
                <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
            </el-row>
            <div id="table" style="margin-top: 20px;">
                <el-table v-loading="tbLoading" ref="alarmTable" :data="tableData" style="width: 100%"
                    @sort-change="sortChange" @filter-change="filterChange">
                    <el-table-column prop="county" label="所属区县" width="120" align="center" fixed />
                    <el-table-column prop="stationNo" label="站号" width="150" align="center" fixed />
                    <el-table-column prop="stationName" label="基站名称" width="420" align="center" fixed />

                    <!-- <el-table-column prop="status" label="状态" width="150" align="center" fixed :filter-multiple="false"
                        :filters="[
                            { text: '正常', value: 1 },
                            { text: '异常', value: 2 },
                        ]" :column-key="'status'" filter-placement="bottom-end">
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" disable-transitions>{{
                                scope.row.status == 1 ? "正常" : "异常" }}</el-tag>
                        </template>
                    </el-table-column> -->
                    <el-table-column prop="createTime" label="创建日期" :formatter="dateFormatter" width="150" fixed="right"
                        align="center" />
                    <el-table-column prop="alarmScore" label="故障告警总分" width="150" fixed="right" align="center"
                        sortable="custom" />
                    <el-table-column fixed="right" label="操作" min-width="250" align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="showAlarmDialog(scope.row.stationNo)">关联告警</el-button>
                            <el-button link type="primary" size="small"
                                @click="showDetailDialog(scope.row.stationNo)">详情</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty :image-size="40" />
                    </template>
                </el-table>
                <!-- <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next" :total="total" @size-change="listAlarmTable"
                    @current-change="listAlarmTable" /> -->
                <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                    @pagination="listAlarmTable" :autoScroll="false" />
            </div>
        </el-card>

        <el-dialog v-model="alarmDialogTableVisible" title="站点相关告警" width="1400" @closed="closeAlarmDialog">
            <el-card style="margin-bottom: 15px;">
                <div style="display: flex">
                    <!-- 只要一个有数据 -->
                    <div class="card-left">
                        <div class="title-name">实时告警等级占比:</div>
                        <div id="chart1" style="width: 520px; height: 240px; margin: -10px 10px 10px 10px" class=""
                            ref="chart1" v-show="!showAll && pie1Flag"></div>
                        <div v-show="!pie1Flag">
                            <el-empty description="无数据" />
                        </div>
                    </div>
                    <div class="card-right">
                        <div class="title-name">过去十日告警等级占比:</div>
                        <div id="chart2" style="width: 520px; height: 240px; margin: -10px 10px 10px 10px" class=""
                            ref="chart2" v-show="!showAll && pie2Flag"></div>
                        <div v-show="!pie2Flag">
                            <el-empty description="无数据" />
                        </div>
                    </div>
                </div>
            </el-card>
            <el-tabs v-model="activeName" @tab-click="handleClick" class="tab_class">
                <el-tab-pane label="实时告警" name="realTimeAlarm">
                    <el-table v-loading="ssgjLoading" ref="realTimeAlarmTable" :data="realTimeAlarmTableData"
                        style="width: 100% ; margin-bottom: 10px;">
                        <el-table-column prop="alarmId" label="告警id" width="200" align="center" />
                        <el-table-column prop="alarmTitle" label="告警标题" width="200" align="center" />
                        <el-table-column prop="eventTime" label="发生时间" width="200" align="center"
                            :formatter="dateTimeFormatter" />
                        <el-table-column prop="alarmStatus" label="告警状态" width="100" align="center">
                            <template #default="scope">
                                <el-tag type='danger' disable-transitions>{{
                                    "未清除" }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="alarmLevel" label="告警等级" width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="fnalarmLevel(scope.row.alarmLevel)" disable-transitions>{{
                                    scope.row.alarmLevel }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="equipmentManufacturerName" label="厂商名称" width="200" align="center" />
                        <el-table-column prop="neName" label="网元名称" width="200" align="center" />
                        <el-table-column prop="standardId" label="标准告警号" width="200" align="center" />
                    </el-table>
                    <!-- <el-pagination v-model:current-page="realCurrentPage" v-model:page-size="realPageSize"
                        :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next" :total="realTotal" @size-change="getRealTimeAlarmList"
                        @current-change="getRealTimeAlarmList" /> -->
                    <pagination v-show="realTotal > 0" :total="realTotal" v-model:page="realCurrentPage"
                        v-model:limit="realPageSize" @pagination="getRealTimeAlarmList" :autoScroll="false" />
                </el-tab-pane>
                <el-tab-pane label="过去十日历史告警" name="historyAlarm">
                    <el-table v-loading="gqsrLoading" ref="historyAlarmTable" :data="historyAlarmTableData"
                        style="width: 100%; margin-bottom: 10px;">
                        <el-table-column prop="alarmId" label="告警id" width="200" align="center" fixed />
                        <el-table-column prop="alarmTitle" label="告警标题" width="300" align="center" fixed />
                        <el-table-column prop="eventTime" label="发生时间" width="200" align="center" fixed
                            :formatter="dateTimeFormatter" />
                        <el-table-column prop="recoveryTime" label="恢复时间" width="200" align="center" fixed
                            :formatter="dateTimeFormatter" />
                        <el-table-column prop="alarmStatus" label="告警状态" width="100" align="center">
                            <template #default="scope">
                                <el-tag type='success' disable-transitions>{{
                                    "已清除" }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="alarmLevel" label="告警等级" width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="fnalarmLevel(scope.row.alarmLevel)" disable-transitions>{{
                                    scope.row.alarmLevel }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="equipmentManufacturerName" label="厂商名称" width="200" align="center" />
                        <el-table-column prop="neName" label="网元名称" width="200" align="center" />
                        <el-table-column prop="standardId" label="标准告警号" width="200" align="center" />
                    </el-table>
                    <!-- <el-pagination v-model:current-page="historyCurrentPage" v-model:page-size="historyPageSize"
                        :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next" :total="historyTotal"
                        @size-change="getHistoryAlarmList" @current-change="getHistoryAlarmList" /> -->
                    <pagination v-show="historyTotal > 0" :total="historyTotal" v-model:page="historyCurrentPage"
                        v-model:limit="historyPageSize" @pagination="getHistoryAlarmList" :autoScroll="false" />
                </el-tab-pane>
            </el-tabs>
        </el-dialog>

        <el-dialog v-model="detailTableVisible" title="故障告警详情" width="1400" @opened="initLineChart"
            @closed="closeDetailDialog">
            <el-card class="card-box" v-loading="xqLoading">
                <el-form :model="queryParams" ref="queryForm" :inline="true">
                    <el-form-item label="时间选择">
                        <el-date-picker v-model="detailDatePicker" type="daterange" style="width: 350px"
                            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" align="right"
                            @change="search"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="detailSearch">查询</el-button>
                    </el-form-item>
                </el-form>
                <div class="card-content" style="display: flex" v-show="!showAll">
                    <div class="card-left">
                        <el-table :data="detailData" style="width: 100%" class="tableBox" max-height="500" id="tableBox"
                            @row-click="handleClickChange" :row-class-name="tableRowClassName">
                            <el-table-column prop="county" label="所属区县" width="120" align="center" />
                            <el-table-column prop="stationNo" label="站号" width="150" align="center" />
                            <el-table-column prop="stationName" label="基站名称" width="250" align="center" />
                            <el-table-column prop="createTime" label="创建时间" width="200" align="center"
                                :formatter="dateFormatter" />
                            <el-table-column prop="alarmScore" label="故障告警总分" width="120" fixed="right"
                                align="center" />
                        </el-table>
                    </div>
                    <div class="card-right">
                        <div class="title-name">分数趋势:</div>
                        <div id="lineChart" style="width: 620px; height: 320px; margin: -10px 20px 20px 40px" class=""
                            ref="lineChart" v-show="!showAll"></div>
                        <div class="data-analyse">
                            <div class="analyse-title">数据分析：</div>
                            <div class="analyse-itemlist">
                                <div class="analyse-item">
                                    <a>所选时间：{{ selectedDays }}天</a>
                                </div>
                                <div class="analyse-item">
                                    <a>故障告警平均分：{{ averageScore.toFixed(2) }}分</a>
                                </div>
                                <div class="analyse-item">
                                    <a>所选时间内最高分：{{ maxScore }}分</a>
                                </div>
                                <div class="analyse-item">
                                    <a>所选时间内最低分:{{ minScore }}分</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </el-dialog>

        <!-- <export-dialog ref="refExportDialog" @directExport="exportData"
            :serviceName="'test MaintenanceServiceImpl.exportEomsOrder'" :type="'test 工单导出'" /> -->
        <export-dialog ref="refExportDialog" @directExport="directExportData" />
    </div>

</template>

<script setup name="networkAlarm">

import { queryAlarm4gResultList, queryAlarm5gResultList, queryRealTimeAlarmList, queryHistoryAlarmList, detailList, queryAlarmOverview, queryAlarmDetail } from '@/api/biz/networkAlarm';
import * as echarts from 'echarts';
import { ref } from 'vue';

import { useConfigStore } from "@/store/modules/config.js";

import qushi from "../chart/qushi.vue";
import quxian from "../chart/quxian.vue";

const { proxy } = getCurrentInstance();
const { nhp_county_type, nhp_network_type } = proxy.useDict("nhp_county_type", "nhp_network_type");

const refExportDialog = ref(null)

let tbLoading = ref(false)

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);
let overviewData = ref({})

const configStoreData = useConfigStore();
let securityFlagConfig = configStoreData.configList.filter(
    (item) => item.configKey === "sys.securityFlag"
)[0];
// console.log("securityFlagConfig", securityFlagConfig);

const setTodayDistrictAverageSort = () => {
    let topThree = overviewData.value.todayDistrictAverage.map((item, index) => ({ ...item, index })).sort((a, b) => b.value - a.value).slice(0, 3)
    let lastThree = overviewData.value.todayDistrictAverage.map((item, index) => ({ ...item, index })).sort((a, b) => b.value - a.value).slice(-3)

    overviewData.value.todayDistrictAverage.push({
        topThree, lastThree,
    })

    topThree.forEach(item => {
        overviewData.value.todayDistrictAverage[item.index].itemStyle = {
            color: '#92cc76'
        }
    })
    lastThree.forEach(item => {
        overviewData.value.todayDistrictAverage[item.index].itemStyle = {
            color: '#a90000'
        }
    })
}

const dataOverview = () => {
    // console.log("dataOverview");
    // 接口
    queryAlarmOverview().then(res => {
        let data = res.data
        // console.log("data", data);

        if (data.dateTime) {
            let current = new Date(data.dateTime).getTime() + 24 * 60 * 60 * 1000
            queryParams.value.createStartEnd = [new Date(data.dateTime), new Date(current)]
            listAlarmTable()
        }

        let timeList = data.timeList;
        let avgScoreList = data.avgScoreList;
        let monthAverage = []
        for (let i = 0; i < timeList.length; i++) {
            var temp = {
                name: timeList[i],
                value: avgScoreList[i]
            }
            monthAverage.push(temp)
        }

        let countyList = data.countyList
        let countyAvgScoreList = data.countyAvgScoreList
        let todayDistrictAverage = []
        for (let i = 0; i < countyList.length; i++) {
            var temp = {
                name: countyList[i],
                value: countyAvgScoreList[i]
            }
            todayDistrictAverage.push(temp)
        }

        // 假数据
        overviewData.value = {
            latestTime: formatDate(data.dateTime),
            todayAverage: data.avgScore,  // 今日平均分
            monthAverage: monthAverage,
            // 今日各区县xxx平均分
            todayDistrictAverage: todayDistrictAverage,
            currentAlarmQuantity: data.realTimeAlarmCount,  // 实时告警数量
        }

        setTodayDistrictAverageSort()
    })
}
dataOverview()

const queryParams = ref({
    networkType: "5G",
    createStartEnd: [new Date(), currentDate],
    exportType: '工单导出',
    // sortContent: 'createTime'
})

const tableData = ref([])
const realTimeAlarmTableData = ref([])
const historyAlarmTableData = ref([])
const detailTableData = ref([])

const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

const realPageSize = ref(10)
const realCurrentPage = ref(1)
const realTotal = ref(0)

const historyPageSize = ref(10)
const historyCurrentPage = ref(1)
const historyTotal = ref(0)

const alarmDialogTableVisible = ref(false)
const detailTableVisible = ref(false)


const activeName = ref('realTimeAlarm')

const currentStationNo = ref("");

const nowOrder = ref();
const nowStatus = ref();

const chart1 = ref(null);
const chart2 = ref(null);
let chartInstance1 = null;
let chartInstance2 = null;

const levelTemp1 = ref([]);
const levelTemp2 = ref([]);
const realTimeAlarmLevel = ref();
const pastAlarmLevel = ref();

const detailDatePicker = ref('');
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
detailDatePicker.value = [start, end];

const detailData = ref([])
const currNetworkType = ref()

let ssgjLoading = ref(false)
let gqsrLoading = ref(false)
let xqLoading = ref(false)

// 重置
function unsetQueryForm() {
    queryParams.value = {
        networkType: "5G",
        county: "",
        stationNo: "",
        stationName: "",
        createTime: [],
        // sortContent: 'createTime'
    }
}

function fnalarmLevel(levelNum) {
    if (levelNum === 1) {
        return "danger";
    } else if (levelNum === 2) {
        return "warning";
    } else if (levelNum === 3) {
        return "primary";
    } else if (levelNum === 4) {
        return "success";
    }
}

// 导出
function exportData() {
    const param = {};
    param.networkType = queryParams.value.networkType;
    param.county = queryParams.value.county;
    param.stationNo = queryParams.value.stationNo;
    param.stationName = queryParams.value.stationName;
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    param.sortContent = "alarmScore";
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    if (securityFlagConfig.configValue == "true") {
        //开启金库模式
        refExportDialog.value.show(param);
    } else {
        proxy.download("/networkAlarm/exportAlarmList", {
            ...param
        }, `故障告警_${new Date().getTime()}.xlsx`);
    }
}

function directExportData() {
    const param = {};
    param.networkType = queryParams.value.networkType;
    param.county = queryParams.value.county;
    param.stationNo = queryParams.value.stationNo;
    param.stationName = queryParams.value.stationName;
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    param.sortContent = "alarmScore";
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    proxy.download("/networkAlarm/exportDirectAlarmList", {
        ...param
    }, `故障告警(剔除敏感数据)_${new Date().getTime()}.xlsx`);
}


function listAlarmTable() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county;
    param.stationName = queryParams.value.stationName;
    param.stationNo = queryParams.value.stationNo;
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    if (queryParams.value.sortContent) {
        param.sortContent = queryParams.value.sortContent;
    }
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString();
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString();
    }
    tbLoading.value = true
    if (queryParams.value.networkType == "5G") {
        //加载5G结果
        queryAlarm5gResultList(param).then(res => {
            tbLoading.value = false
            currNetworkType.value = "5G"
            tableData.value = res.rows;
            total.value = res.total;
        })
    } else if (queryParams.value.networkType == "4G") {
        //加载4G结果
        queryAlarm4gResultList(param).then(res => {
            tbLoading.value = false
            currNetworkType.value = "4G"
            tableData.value = res.rows;
            total.value = res.total;
        })
    }
}

async function showAlarmDialog(stationNo) {
    alarmDialogTableVisible.value = true;
    currentStationNo.value = stationNo;
    getAlarmDetail()
    //获取告警信息
    getRealTimeAlarmList()
    getHistoryAlarmList()

}

// 无数据false，有数据true
let pie1Flag = ref(true)
let pie2Flag = ref(true)

function getAlarmDetail() {
    let param = {
        stationNo: currentStationNo.value,
        networkType: currNetworkType.value
    }
    queryAlarmDetail(param).then(res => {
        let realTimeAlarmLevelMap = res.data.realTimeAlarmLevelMap
        let historyAlarmLevelMap = res.data.historyAlarmLevelMap

        if (!realTimeAlarmLevelMap || JSON.stringify(realTimeAlarmLevelMap) === "{}") {
            pie1Flag.value = false
        } else {
            pie1Flag.value = true
        }
        if (!historyAlarmLevelMap || JSON.stringify(historyAlarmLevelMap) === "{}") {
            pie2Flag.value = false
        } else {
            pie2Flag.value = true
        }
        // console.log(pie1Flag.value, pie2Flag.value)

        let tempRealTimeAlarmLevel = []
        // 定义一个包含所有期望键的数组  
        let keys = [1, 2, 3, 4];

        // 遍历这个数组  
        keys.forEach(key => {
            // 将键转换为字符串，因为 realTimeAlarmLevelMap 的键是字符串类型  
            let strKey = key.toString();
            // 检查 realTimeAlarmLevelMap 中是否存在该键  
            if (realTimeAlarmLevelMap.hasOwnProperty(strKey)) {
                // 如果存在，则 push 对应的值  
                tempRealTimeAlarmLevel.push(realTimeAlarmLevelMap[strKey]);
            } else {
                // 如果不存在，则 push 0  
                tempRealTimeAlarmLevel.push(0);
            }
        });

        let tempHistoryAlarmLevel = []
        keys.forEach(key => {
            let strKey = key.toString();
            if (historyAlarmLevelMap.hasOwnProperty(strKey)) {
                // 如果存在，则 push 对应的值  
                tempHistoryAlarmLevel.push(historyAlarmLevelMap[strKey]);
            } else {
                // 如果不存在，则 push 0  
                tempHistoryAlarmLevel.push(0);
            }
        });

        realTimeAlarmLevel.value = tempRealTimeAlarmLevel
        pastAlarmLevel.value = tempHistoryAlarmLevel

        initChart()
    })
}

const handleClick = (tab, event) => {
    const { label } = tab.props
    switch (label) {
        case '实时告警':
            getRealTimeAlarmList()
            break;
        case '历史告警':
            getHistoryAlarmList()
            break;
    }
}

function getRealTimeAlarmList() {
    let param = {
        stationNo: currentStationNo.value,
        pageSize: realPageSize.value,
        pageNum: realCurrentPage.value,
        networkType: currNetworkType.value
    }
    ssgjLoading.value = true;
    queryRealTimeAlarmList(param).then(res => {
        ssgjLoading.value = false;
        realTimeAlarmTableData.value = res.rows;
        realTotal.value = res.total;
    })
}


function getHistoryAlarmList() {
    let param = {
        stationNo: currentStationNo.value,
        pageSize: historyPageSize.value,
        pageNum: historyCurrentPage.value,
        networkType: currNetworkType.value
    }
    gqsrLoading.value = true;
    queryHistoryAlarmList(param).then(res => {
        gqsrLoading.value = false;
        historyAlarmTableData.value = res.rows;
        historyTotal.value = res.total;
    })

}



function getPieData(levelTemp) {
    var tempData = levelTemp.reduce((accumulator, currentValue) => {
        if ([1, 2, 3, 4].includes(currentValue)) {
            accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
        }
        return accumulator;
    }, {});
    return tempData;
}

// 饼状图
function initChart() {
    chartInstance1 = echarts.init(chart1.value);
    chartInstance2 = echarts.init(chart2.value);

    drawChart();
}

function drawChart() {
    // realTimeAlarmLevel.value = getPieData(levelTemp1.value);
    // pastAlarmLevel.value = getPieData(levelTemp2.value);
    var pieData1 = [
        {
            name: '一级告警',
            value: realTimeAlarmLevel.value[0] === 0 ? undefined : realTimeAlarmLevel.value[0]
        }, {
            name: '二级告警',
            value: realTimeAlarmLevel.value[1] === 0 ? undefined : realTimeAlarmLevel.value[1]
        }, {
            name: '三级告警',
            value: realTimeAlarmLevel.value[2] === 0 ? undefined : realTimeAlarmLevel.value[2]
        }, {
            name: '四级告警',
            value: realTimeAlarmLevel.value[3] === 0 ? undefined : realTimeAlarmLevel.value[3]
        },
    ];
    var pieData2 = [
        {
            name: '一级告警',
            value: pastAlarmLevel.value[0] === 0 ? undefined : pastAlarmLevel.value[0]
        }, {
            name: '二级告警',
            value: pastAlarmLevel.value[1] === 0 ? undefined : pastAlarmLevel.value[1]
        }, {
            name: '三级告警',
            value: pastAlarmLevel.value[2] === 0 ? undefined : pastAlarmLevel.value[2]
        }, {
            name: '四级告警',
            value: pastAlarmLevel.value[3] === 0 ? undefined : pastAlarmLevel.value[3]
        },
    ];

    const setOption = (data) => {
        return {
            color: ['#ef6567', '#fc8251', '#5470c6', '#91cd77',],
            series: [
                {
                    type: 'pie', // 类型： 饼图
                    data,
                    label: {//饼图文字的显示
                        show: true, //默认  显示文字
                        formatter: function (arg) {
                            return arg.name + ' 有 ' + arg.value + " 条" + '\n' + '占比' + arg.percent + "%"
                        }
                    },
                    selectedMode: 'multiple',
                    selectedOffset: 30,
                    radius: ['50%', '80%']
                }
            ]
        }
    }
    chartInstance1.setOption(setOption(pieData1));
    chartInstance2.setOption(setOption(pieData2));
}

// 打开详情页
function showDetailDialog(stationNo) {
    detailTableVisible.value = true;
    currentStationNo.value = stationNo;
    //获取该站点的故障告警历史得分列表
    listDetailTable(currentStationNo.value);
}

// 详情页列表
async function listDetailTable(stationNo) {
    const param = {};
    param.stationNo = stationNo;
    param.createStart = formatDate(detailDatePicker.value[0]);
    param.createEnd = formatDate(detailDatePicker.value[1]);
    param.networkType = currNetworkType.value
    param.sortContent = 'createTime'
    param.order = 'ascending'
    xqLoading.value = true;
    await detailList(param).then(res => {
        xqLoading.value = false;
        detailData.value = res.data;
    })
    initLineChart();
}

function detailSearch() {
    listDetailTable(currentStationNo.value);
}

// 格式化日期
function formatDateTime(dateString) {
    if (!dateString) return
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数  
    const day = date.getDate().toString().padStart(2, '0'); // 使用 padStart 来确保日期是两位数  
    var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数  
    const day = date.getDate().toString().padStart(2, '0'); // 使用 padStart 来确保日期是两位数  
    return `${year}-${month}-${day}`;
}

// 折线图
const lineChart = ref(null);
let lineChartInstance = null;

function initLineChart() {
    lineChartInstance = echarts.init(lineChart.value);
    drawLineChart();
    calculateStatistics();
}

function drawLineChart() {
    const xData = detailData.value.map(item => dateFormatter(null, null, item.createTime, null)); // 创建时间数组  
    const yData = detailData.value.map(item => item.alarmScore); // 网络质量总分数组  

    const options = {
        tooltip: {
            trigger: "axis",
        },
        grid: {
            left: "5%",
            right: "15%",
            bottom: "0%",
        },
        xAxis: {
            type: 'category',
            data: xData,
        },
        yAxis: {
            type: 'value',
        },
        series: [{
            data: yData,
            type: 'line',
            smooth: true,
        }],
    };
    lineChartInstance.setOption(options);
}

const selectedDays = ref(0);
const averageScore = ref(0);
const maxScore = ref(0);
const minScore = ref(0);
function calculateStatistics() {
    if (detailData.value.length > 0) {
        const scores = detailData.value.map(item => item.alarmScore);
        const startDate = new Date(detailDatePicker.value[0]);
        const endDate = new Date(detailDatePicker.value[1]);
        const diffTime = endDate - startDate;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        selectedDays.value = diffDays + 1;
        averageScore.value = scores.reduce((sum, score) => sum + score, 0) / scores.length;
        maxScore.value = Math.max(...scores);
        minScore.value = Math.min(...scores);
    } else {
        averageScore.value = 0;
        maxScore.value = 0;
        minScore.value = 0;
    }
}

function closeAlarmDialog() {
    alarmDialogTableVisible.value = false
    currentStationNo.value = ""
    realTimeAlarmTableData.value = []
    realCurrentPage.value = 1
    realTotal.value = 0
    realPageSize.value = 10

    historyAlarmTableData.value = []
    historyCurrentPage.value = 1
    historyTotal.value = 0
    historyPageSize.value = 10
    activeName.value = "realTimeAlarm";
    levelTemp1.value = [];
    levelTemp2.value = [];
    console.log("alarmDialogTableVisible : " + alarmDialogTableVisible.value);
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day;
    return formattedDateTimeString;
}

function dateTimeFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return formattedDateTimeString;
}


// 总分排序
function sortChange(column, prop, order) {
    console.log(111)
    nowOrder.value = column.order;
    queryParams.value.sortContent = 'alarmScore'
    listAlarmTable();
}
// 筛选状态
function filterChange(filters) {
    nowStatus.value = filters.status[0];
    listAlarmTable();
}

listAlarmTable();


</script>

<style>
.card-box {
    padding: 0px;
}

.card-left {
    width: 50%;
}

.title-name {
    justify-content: space-between;
    font-size: 14px;
    font-weight: bold;
}

.card-right {
    margin-left: 20px;
    width: 50%;
    /* border: 1px solid #000; */
}

.data-analyse {
    margin: 10px;
    height: 100px;
    width: 300px;

    .analyse-title {
        height: 50px;
        padding: 10px 10px 0px 10px;
        font-weight: bold;
        font-size: 14px;
    }

    .analyse-itemlist {
        height: 60px;
        width: 600px;
        margin-left: 50px;
        font-size: 14px;
        display: flex;
        flex-wrap: wrap;
    }

    .analyse-item {
        min-width: 300px;
        height: 30px;
        margin: 0px;
        padding: 0px;
        font-size: 15px;
    }
}

.tab_class {
    .el-tabs__content {
        padding-bottom: 36px;
    }
}
</style>